# -*- encoding: utf-8 -*-
import xmltodict
import thread
from types import *
from datetime import datetime
from peliculas.models import Movie, Genre, Director, Actor, PurchaseOption, Score
from django.shortcuts import render
from django import http, forms
import xml.etree.ElementTree as ET

# import para búsqueda
from django.db.models import Q
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import operator
# end import para búsqueda

class SimpleFileForm(forms.Form):
    file = forms.Field(widget=forms.FileInput, required=False)

def monster(request):
	carrusel = Movie.objects.filter(year = 2014, classificationAdult = False)[:10]
	movies = Movie.objects.all()[:6]
	genero = Genre.objects.all().exclude(genreName = 'Cine adulto').order_by('genreName')
	
	action_genre = Genre.objects.filter(genreName = 'Acción')
	drama_genre = Genre.objects.filter(genreName = 'Drama')
	romanticas_genre = Genre.objects.filter(genreName = 'Románticas')

	action_movies = Movie.objects.filter(genre = action_genre, classificationAdult = False).order_by('year')
	drama_movies = Movie.objects.filter(genre = drama_genre, classificationAdult = False).order_by('year','?')

	romanticas_movies = Movie.objects.filter(genre = romanticas_genre, classificationAdult = False).order_by('year')
    
	sd = PurchaseOption.objects.filter(offerType__icontains = "rent", videoQuality = 'SD')
	
	movs = []
	for po in sd:
		movs.append(po.movie)
	
	action_movies = list(set(action_movies).intersection(movs))
	action_movies.sort(key=lambda x: x.title, reverse=False)
	
	drama_movies = list(set(drama_movies).intersection(movs))
	drama_movies.sort(key=lambda x: x.title, reverse=False)

	romanticas_movies = list(set(romanticas_movies).intersection(movs))
	romanticas_movies.sort(key=lambda x: x.title, reverse=False)

	romanticas_movies = romanticas_movies[:6]
    
	drama_movies = drama_movies[:6]
	action_movies =action_movies[:6]
	
	context = {'movies':movies, 'carrusel':carrusel, 'categoria': genero, 'action_movies':action_movies, 'drama_movies':drama_movies, 'romanticas_movies':romanticas_movies}
	return render(request, 'monster/index.html', context)


def categoria(request, idGenre):
    
	PELICULAS_POR_PAGINA = 8
	page = request.GET.get('page')

	generoSeleccionado = Genre.objects.get(id = idGenre)
	movies_list = Movie.objects.filter(genre = generoSeleccionado, classificationAdult = False).order_by('year')
	
	sd = PurchaseOption.objects.filter(offerType__icontains = "rent", videoQuality = 'SD')
	
	movs = []
	for po in sd:
		movs.append(po.movie)
	
	movies_list = list(set(movies_list).intersection(movs))
	movies_list.sort(key=lambda x: x.title, reverse=False)
	
	
	nombreGenero = Genre.objects.get(id = idGenre)
	
	genero = Genre.objects.all().exclude(genreName = 'Cine adulto').order_by('genreName')
	
	pelis = []
	paginator = Paginator(movies_list, PELICULAS_POR_PAGINA)
	try:
		pelis = paginator.page(page)
	except PageNotAnInteger:
		pelis = paginator.page(1)
	except EmptyPage:
		pelis = paginator.page(paginator.num_pages)

	context = {'movies_por_categoria':pelis, 'nombreGenero':nombreGenero.genreName, 'categoria': genero, 'genero': generoSeleccionado}
	return render(request, 'monster/categoria.html', context)
 
def infoPeli(request, idPeli):

    movie = Movie.objects.get(id_XML = idPeli)
    novedades = Movie.objects.filter(year = 2014, classificationAdult = False).order_by('?')
    
    sd = PurchaseOption.objects.filter(offerType__icontains = "rent", videoQuality = 'SD')
	
    movs = []
    for po in sd:
        movs.append(po.movie)
	
    novedades = list(set(novedades).intersection(movs))
    novedades.sort(key=lambda x: x.title, reverse=False)
	
    novedades = novedades[:2]
	
    relacionadas = Movie.objects.none()
    
    for g in movie.genre.all():
        relacionadas = relacionadas | Movie.objects.filter(genre = g, classificationAdult = False).order_by('year')
    
    relacionadas = list(set(relacionadas).intersection(movs))
    
    relacionadas = relacionadas[:15]
    
    context = {'pelicula': movie, 'novedad': novedades, 'relacionadas': relacionadas}
    return render(request, 'monster/infoPeli.html', context)



 
def busqueda(request):

	genero = Genre.objects.all().exclude(genreName = 'Cine adulto').order_by('genreName')
	novedades = Movie.objects.filter(year = 2014, classificationAdult = False)
	
	sd = PurchaseOption.objects.filter(offerType__icontains = "rent", videoQuality = 'SD')
	
	movs = []
	for po in sd:
		movs.append(po.movie)
	
	novedades = list(set(novedades).intersection(movs))
	novedades.sort(key=lambda x: x.title, reverse=False)
	
	novedades = novedades[:2]
	
	PELICULAS_POR_PAGINA = 8
	page = request.GET.get('page')
	genres = Genre.objects.all().exclude(genreName = 'Cine adulto').order_by('genreName')
	busqueda = ""
	edades = ["T", "+7", "+13", "+16", "+18"]
	peliculas = []
	resultado = False
	title = request.GET.get('title','')
	year = request.GET.get('year','')
	fromyear = request.GET.get('fromyear','')
	toyear = request.GET.get('toyear','')
	genre = request.GET.get('genre','')
	actor = request.GET.get('actor','')
	director = request.GET.get('director','')
	age = request.GET.get('age','')
	premiere = request.GET.get('premiere','')
	query = []
	query.append( Q(**{'classificationAdult':False} ) ) 
	if title:
		query.append( Q(**{'title__icontains':title} ) ) 
		busqueda += 'title=' + title + '&'
		resultado = True
	if year:
		query.append( Q(**{'year':year} ) ) 
		busqueda += 'year=' + year + '&'
		resultado = True
	if genre:
		gs = Genre.objects.filter(genreName__icontains = genre)
		query.append( Q(**{'genre':gs} ) ) 
		busqueda += 'genre=' + genre + '&'
		resultado = True
	if actor:
		acs = Actor.objects.filter(actorName__icontains = actor)
		query.append( Q(**{'actor':acs} ) ) 
		busqueda += 'actor=' + actor + '&'
		resultado = True
	if director:
		dires = Director.objects.filter(directorName__icontains = director)
		query.append( Q(**{'director':dires} ) ) 
		busqueda += 'director=' + director + '&'
		resultado = True
	if age:
		query.append( Q(**{'classificationName__icontains':age} ) ) 
		busqueda += 'age=' + age + '&'
		resultado = True
	if fromyear:
		query.append( Q(**{'year__gte':fromyear} ) ) 
		busqueda += 'fromyear=' + fromyear + '&'
		resultado = True
	if toyear:
		query.append( Q(**{'year__lte':toyear} ) ) 
		busqueda += 'toyear=' + toyear + '&'
		resultado = True
	if premiere == 'true':
		pre = PurchaseOption.objects.filter(offerType__icontains = "rent", price = 3.99, videoQuality = 'SD')
		busqueda += 'premiere=' + premiere + '&'
		movs = []
		for po in pre:
			movs.append(po.movie)
		resultado = True
	elif premiere == 'false':
		pre = PurchaseOption.objects.filter(offerType__icontains = "rent", price = 1.99, videoQuality = 'SD')
		busqueda += 'premiere=' + premiere + '&'
		movs = []
		for po in pre:
			movs.append(po.movie)
		resultado = True
	else:
		pre = PurchaseOption.objects.filter(offerType__icontains = "rent", videoQuality = 'SD')
		movs = []
		for po in pre:
			movs.append(po.movie)
	pelis = []
	if resultado:
		peliculas = Movie.objects.filter(reduce(operator.and_, query))
		peliculas = list(set(peliculas).intersection(movs))
		peliculas.sort(key=lambda x: x.title, reverse=False)
		paginator = Paginator(peliculas, PELICULAS_POR_PAGINA)
		try:
			pelis = paginator.page(page)
		except PageNotAnInteger:
			pelis = paginator.page(1)
		except EmptyPage:
			pelis = paginator.page(paginator.num_pages)

	context = {"genres":genres, "edades":edades, "peliculas":pelis, "resultado":resultado, "busqueda":busqueda, "title":title, "fromyear":fromyear, "toyear":toyear, "genre":genre, "actor":actor, "director":director,"age":age, "premiere":premiere, 'categoria': genero, 'novedad': novedades}
	return render(request, 'monster/busqueda.html', context)	

def index(request):
	if request.method == 'POST':
		if 'file' in request.FILES:
			file = request.FILES['file']
			filecontent = file.read()
			root = ET.fromstring(filecontent)
			for child in root:
				if child.tag == 'Movie':
					correct = True
					m = Movie()
					try:
						m.id_XML = child.find('Id').text
					except AttributeError:
						correct = False
					try:
						mm = Movie.objects.get(id_XML = m.id_XML)
					except Movie.DoesNotExist:
						try:
							m.title = child.find('Title').text
						except AttributeError:
							correct = False
						try:
							m.plot = child.find('Plot').text
						except AttributeError:
							correct = False
						try:
							m.publicWebUri = child.find('PublicWebUri').text
						except AttributeError:
							correct = False
						try:
							modifiedDate = child.find('LastModifiedDate').text
							m.lastModifiedDate = datetime.strptime(modifiedDate[:21], '%Y-%m-%dT%I:%M:%S.%f')
						except (AttributeError, KeyError, TypeError, ValueError):
							m.lastModifiedDate = datetime.now()
						try:
							originalPublicationDate = child.find('OriginalPublicationDate').text
							m.originalPublicationDate = datetime.strptime(modifiedDate[:21], '%Y-%m-%dT%I:%M:%S.%f')
						except (AttributeError, KeyError, TypeError, ValueError):
							m.originalPublicationDate = datetime.now()
						try:
							m.artwork = child.find('Artwork').text
						except (AttributeError, KeyError, TypeError):
							correct = False
						try:
							m.classificationName = child.find('Classification').find('Name').text
							if child.find('Classification').find('Adult').text == 'false':
								m.classificationAdult = False
							else:
								m.classificationAdult = True
						except (AttributeError, KeyError, TypeError):
							correct = False
						try:
							m.year = child.find('Year').text
						except (AttributeError, KeyError, TypeError):
							correct = False
						try:
							m.duration = child.find('Duration').text
						except (AttributeError, KeyError, TypeError):
							m.duration = '-'
						m.save()
						try:
							for gname in child.find('Genres'):
								genre = gname.text
								try:
									g = Genre.objects.get(genreName = genre)
								except Genre.DoesNotExist:
									g = Genre()
									g.genreName = genre
									g.save()
								m.genre.add(g)
						except (AttributeError, KeyError, TypeError):
							pass
						try:
							for dname in child.find('Directors'):
								director = dname.find('Name').text
								try:
									d = Director.objects.get(directorName = director)
								except Director.DoesNotExist:
									d = Director()
									d.directorName = director
									d.save()
								m.director.add(d)
						except (AttributeError, KeyError, TypeError):
							pass
						try:
							for aname in child.find('Actors'):
								actor = aname.find('Name').text
								try:
									a = Actor.objects.get(actorName = actor)
								except Actor.DoesNotExist:
									a = Actor()
									a.actorName = actor
									a.save()
								m.actor.add(a)
						except (KeyError, TypeError):
							pass
						try:
							for p in child.find('PurchaseOptions'):
								po = PurchaseOption()
								po.offerType =  p.find('OfferType').text
								po.price =  p.find('Price').text
								po.currency =  p.find('Currency').text
								po.videoQuality =  p.find('VideoQuality').text
								po.movie = m
								po.save()
						except (KeyError, TypeError):
							pass
						try:
							for p in child.find('Scores'):
								sco = Score()
								sco.scoreValue = p.find('Value').text
								sco.scoreUrl = p.find('Url').text
								sco.movie = m
								sco.save()
						except (KeyError, TypeError):
							pass


			
				
			context = {'upload':True}
			return render(request, 'index.html', context)
	else:
		# display the form
		form = SimpleFileForm()
		context = {'upload':False, 'form':form}
		return render(request, 'index.html', context)
